-- https://mp.weixin.qq.com/s/___________________

local ffi = require "ffi"
local ffistr = ffi.string
local ffichars = ffi.typeof "char[?]"
ffi.cdef[[
int __stdcall MultiByteToWideChar(int,int,const char*,int,char*,int);
int __stdcall WideCharToMultiByte(int,int,const char*,int,char*,int,const char*,int*);
]]
local C = ffi.C

local function mb2wc(src, cp)
	local srclen = #src
	local dst = ffichars(srclen * 2)
	return ffistr(dst, C.MultiByteToWideChar(cp or 65001, 0, src, srclen, dst, srclen) * 2)
end

local function wc2mb(src, cp)
	local srclen = #src / 2
	local dstlen = srclen * 3
	local dst = ffichars(dstlen)
	return ffistr(dst, C.WideCharToMultiByte(cp or 65001, 0, src, srclen, dst, dstlen, nil, nil))
end

local function fixFileName(name)
	return name:gsub("[:*?\"<>|]", "_")
end

local function exec(cmd)
	local f = io.popen(cmd)
	if not f then return "" end
	local s = f:read "*a"
	f:close()
	return s
end

local html = exec("curl -k -L -A \"Mozilla/5.0\" \"" .. arg[1] .. "\"")
local title = html:match [[<meta property="og:title" content="(.-)"]]
if not title then
	error "ERROR: not found title"
end
title = fixFileName(wc2mb(mb2wc(title, 65001), 1))
print(title)
local bestUrl
for url in html:gmatch [[url: %(?'(.-)']] do
	url = url:gsub("\\x(%w%w)", function(a) return string.char(tonumber(a, 16)) end)
	url = url:gsub("&amp;", "&")
	if url:find "%.mp4" then
		print(url)
		if not bestUrl then
			bestUrl = url
			if not arg[2] then
				break
			end
		end
	end
end

if title and bestUrl and not arg[2] then
	os.execute("curl -k -L -A \"Mozilla/5.0\" -o \"" .. title .. ".mp4" .. "\" \"" .. bestUrl .. "\"")
end
